/*
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2023-04-04 11:34:17
 * @LastEditTime: 2023-05-16 23:29:48
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 字典存储器
 * @FilePath: \vue3-element-plus-web\src\store\modules\dictData.js
 * @Copyright 版权声明
 */
import { getDictTree } from '@/api/SysManage/sysDict.js'

const dictData = {
  state: {
    /**
     * @description 字典存储器
     */
    dictData: {

    }
  },

  mutations: {
    // 字典存储器
    SET_DICT_DATA: (state, { code, data }) => {
      state.dictData[code] = data
    }
  },

  actions: {
    /**
     * 通过字典码（code）获取【字典管理中的字典项】
     * @param {String} code 字典项在系统内唯一标识
     * @param {Integer} nodeLevel 获取几层,默认不限制
     * @returns
     */
    GET_DICT_LIST({ commit }, { code = '', nodeLevel = 9999 }) {
      if (code === '') {
        throw new Error(`store.dispatch('GET_DICT_LIST') 方法的 code 参数不能为空`)
      }
      if (!Number.isInteger(nodeLevel)) {
        throw new Error(`store.dispatch('GET_DICT_LIST') 方法的 nodeLevel 参数需要传入数字`)
      }
      return new Promise((resolve) => {
        getDictTree({
          code
        }).then((res) => {
          const resData = res.data || []
          // 递归生成字典树
          const buildTree = (arr, level) => {
            level++
            const buildArr = []
            for (const i in arr) {
              const item = {
                value: arr[i].dictKey,
                label: arr[i].dictValue
              }
              if (level < nodeLevel && typeof arr[i].children !== 'undefined' && (arr[i].children).length > 0) {
                item.children = buildTree(arr[i].children, level)
              }
              buildArr.push(item)
            }
            return buildArr
          }
          const dataArr = buildTree(resData, 0)
          commit('SET_DICT_DATA', {
            code,
            data: dataArr
          })
          resolve(dataArr)
        })
      })
    },
    /**
     * 设置字典项目，用于非【字典管理】模块中维护的字典数据
     * @param {String} code 字典项在系统内唯一标识
     * @param {Array} data 字典数据
     * @returns
     */
    SET_DICT_LIST({ commit }, { code = '', data = [] }) {
      return new Promise((resolve) => {
        commit('SET_DICT_DATA', {
          code,
          data
        })
        resolve(data)
      })
    }
  }
}

export default dictData
